import Taro from '@tarojs/taro'
import { WX_USER_INFO, USER_MAP_PIN, USER_MONEY, MONEY_HISTORY, USER_CHECKIN } from '../constants/user'
import { queryUserInfo, queryMoneyLog, getTensecondTimes } from '../api/user'

// 设置 通过 wx.getUserInfo 获取到的用户公开信息
export const setWxUserInfo = (data) => {
  return {
    type: WX_USER_INFO,
    data
  }
}

// 设置用户选择的定位位置
export const setUserMapPin = (location) => {
  return {
    type: USER_MAP_PIN,
    location
  }
}

// 设置用户选择的定位位置
export const setUserMoney = (money,name,phone) => {
  return {
    type: USER_MONEY,
    money,
    name,
    phone
  }
}

// 设置 用户的余额记录
export const setMoneyLog = ({money_history, money_history_page}) => {
  return {
    type: MONEY_HISTORY,
    money_history,
    money_history_page
  }
}

// 清理用户的余额记录
export const resetMoneyLog = () => {
  return {
    type: MONEY_HISTORY,
    money_history: [],
    money_history_page: 1
  }
}

// 设置 用户是否可签到
export const setUserCheckin = (checkin) => {
  console.log(checkin)
  const now = new Date()
  const date = `${now.getFullYear()}${('0' + (now.getMonth() + 1)).slice(-2)}${('0' + now.getDate()).slice(-2)}`
  Taro.setStorageSync('checkin' + date, '1') // 表示今天已经设置过签到了
  return {
    type: USER_CHECKIN,
    checkin
  }
}

// 异步的action 获取用户余额
export function asyncUserMoney () {
  return (dispatch, getState)  => {
    const { token } = getState().user
    if (!token) return // TODO 二者不在的处理
    const shop_id = Taro.getStorageSync('shop_id')
    queryUserInfo(token,shop_id).then(({data, status}) => {
      if (status) {
        const {money,name,phone} = data
        dispatch(setUserMoney(
          money, // 用户余额
          name,
          phone
         
        ))
      }
    })
  }
}

// 异步的action 获取用户余额记录
export function asyncUserMoneyLog () {
  return (dispatch, getState)  => {
    const { token, money_history_page, money_history } = getState().user
    if (!token) return
    queryMoneyLog(token, money_history_page).then(({data, status}) => {
      console.log(data)
      if (status) {
        dispatch(setMoneyLog({
          money_history: [...money_history, ...data],
          money_history_page: money_history_page + 1
        }))
      }
    })
  }
}

// 异步的action 获取用户是否可以签到
export function asyncUserCheckinInfo () {
  return (dispatch, getState)  => {
    const { token } = getState().user
    if (!token) return
    getTensecondTimes(token).then(({data, status}) => {
      if (status) {
        // dispatch(setUserCheckin({
        //   checkin: parseInt(data, 10) > 0
        // }))
         dispatch(setUserCheckin(parseInt(data, 10) > 0))
      }
    })
  }
}
